<!-- 验证插件 -->
<script src="/static/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="/static/plugins/jquery-validation/localization/messages_zh.min.js"></script>
<!-- 针对当前主题进行简单封装，精简代码 -->
<script src="/static/sdtheme/scripts/sdvalidate.js"></script>

<!-- datepicker -->
<script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>
<!-- timepicker -->
<script src="/static/plugins/timepicker/bootstrap-timepicker.js"></script>

<!-- 不再使用腾讯地图，使用高德地图 -->
<script charset="utf-8" src="https://webapi.amap.com/maps?v=2.0&key=88f3d7038aab501b651c06f1e691a97a"></script>

<script src="/static/plugins/typeahead/js/bootstrap3-typeahead.js"></script>

<script src="/static/plugins/ajaxfileupload.js"></script>
<script src="/static/plugins/bootstrap-fileinput-jasny/bootstrap-fileinput.js"></script>

<script>
    var index = parent.layer.getFrameIndex(window.name);
    var $input = $('#city');
    var $keyword = $('#keyword');
    var $searchForm = $('#searchForm');

    $(function () {
        pageInit();
        initMap();
        $('#LessonTime').timepicker({
            minuteStep: 1,
            secondStep: 5,
            showInputs: false,
            modalBackdrop: true,
            showSeconds: true,
            showMeridian: false
        });
        loadCityData();
        initUpload()
    });

    function initUpload() {
        $('.btn-file').on('change.bs.fileinput', function () {
            var fileInput = $('input[type="file"]', this);
            console.log(fileInput)
            var inputId = fileInput.attr('id');
            console.info(inputId)
            var hiddenInput = $('#' + inputId.replace('input', ''));

            $.ajaxFileUpload({
                url: '{{urlfor "AttachmentController.UploadMinio"}}',
                secureuri: false,
                fileElementId: inputId,
                dataType: 'json',
                data: {
                    keyword: fileInput.attr('name')
                },
                complete: function () {

                },
                success: function (res, status) {
                    if (res.code === 0) {
                        hiddenInput.val(res.obj);
                    } else {
                        parent.layer.alert(res.msg, {icon: 2, title: '错误'})
                        hiddenInput.val('')
                    }
                },
                error: function (XHR, status, e) {
                    sdtheme.alertXHRError(XHR);
                    hiddenInput.val('')
                }
            });
        })
    }

    function initMap() {
        //地图加载
        var map = new AMap.Map("container", {
            resizeEnable: true
        });
        //输入提示
        var autoOptions = {
            input: "searchAddress"
        };

        AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
            var auto = new AMap.AutoComplete(autoOptions);
            var placeSearch = new AMap.PlaceSearch({
                map: map
            });  //构造地点查询类
            auto.on("select", select);//注册监听，当选中某条记录时会触发
            function select(e) {
                placeSearch.setCity(e.poi.adcode);
                placeSearch.search(e.poi.name);  //关键字查询查询
                console.log(e);
                $('#Lng').val(e.poi.location.lng);
                $('#Lat').val(e.poi.location.lat);
                var address = e.poi.district + e.poi.address;
                $('#Address').val(address);
            }
        });
        //点击地图事件
        map.on('click', function (e) {
            console.log(e);
            var lat = e.lnglat.getLat();
            var lng = e.lnglat.getLng();
            $('#Lng').val(lng);
            $('#Lat').val(lat);
        })
    }
    
    function pageInit() {
        $("#Status").selectpicker('val', '{{.m.Status}}');
        $("#IsRecommend").selectpicker('val', '{{.m.IsRecommend}}');
        validateInfo();
        loadDatepicker()
    }

    function loadCityData() {
        $.ajax({
            url: '{{ urlfor "CourseController.GetCityData" }}',
            dataType: 'json',
            success: function (res) {
                if (res.code === 0) {
                    $input.typeahead({
                        source: res.obj,
                        autoSelect: true
                    });
                    $input.change(function () {
                        var current = $input.typeahead("getActive");
                        if (current) {
                            if (current.name === $input.val()) {
                                $('#cityValue').val(current.name)
                            }
                        }
                    })
                }
            }
        })
    }

    function validateInfo() {
        var $thisForm = $('#thisForm');
        $thisForm.sdvalidate({
            rules: {
                CourseName: {
                    maxlength: 150,
                    required: true
                }
            },
            submitHandler: function (form) {
                var url = '{{ urlfor "CourseController.Edit" }}';
                var params = $thisForm.serialize();
                $.sdpost(url, params, function (res) {
                    if (res.code === 0) {
                        parent.layer.msg(res.msg);
                        parent.refresh(res.obj)
                        parent.layer.close(index)
                    } else {
                        parent.layer.alert(res.msg, {icon: 2, title: '失败'})
                    }
                });
                return false
            }
        });
    }

    $('#btnSearch').on('click', function () {
        console.log('click #search')
        var address = $('#searchAddress').val();
        if (!address) return;
        $.ajax({
            url: '{{urlfor "CourseController.GetAddress"}}',
            data: {
                address: address,
                region: ''
            },
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.obj.status === 0) {
                    var result = res.obj.result;
                } else {
                    console.log(res.obj.message)
                }
            }
        })
    });

    function searchMapCallback(res) {
        console.log(res)
    }

    $('#btnClearSearch').on('click', function () {
        $('#searchAddress').val('');
    });

    function loadDatepicker() {
        // The Calender
        $('#StartTime').datepicker({
            language: 'zh-CN',       //语言
            todayHighlight: true,    //今天高亮
            format: 'yyyy-mm-dd'
        });

        $('#DeadLine').datepicker({
            language: 'zh-CN',       //语言
            todayHighlight: true,    //今天高亮
            format: 'yyyy-mm-dd'
        });
    }

    function FormSubmit() {
        $('#thisForm').submit()
    }
</script>